/**
 * JAVACC DEMO 1.0
 */
package com.apache.ius;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.datasource.DynamicDataSource;
import com.apache.database.datasource.DynamicDataSourceHolder;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusSqlPorxyPlugin;
import com.apache.tools.DataMap;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  插件组合拦截处理插件实现类
 *
 * @author dyhou 创建时间：2016-10-11
 */
public class IusSqlPorxyPluginImpl implements IusSqlPorxyPlugin {

	protected Logger log = Logger.getLogger(getClass());

	private IDao iusPubDao;

	private Map<String, String> plugins = new HashMap<String, String>(1);

	private final String plugins_cache_key = "plugin_";

	public Object doInvoke(ParamsVo vo) {
		String key = String.valueOf(vo.getParams("sqlKeyId"));
		String methodKey = vo.getMethodKey();
		vo.setMethodKey("");
		if (Validator.isNull(methodKey))
			return null;
		String str = getPlugins(key);//.get(key);
		Map resultmap = new HashMap();
		if (Validator.isNotNull(str)) {
			String strs[] = str.split(",");
			for (int i = 0; i < strs.length; i++) {//循环处理拦截插件
				CustomMethodPlugin plugin = CustomMethodFactory.getInstance().getPluginByKey(strs[i]);
				if (null == plugin)
					return null;
				Map map = null;
				if (Validator.isNotNull(methodKey) && "beforMethodKey".equalsIgnoreCase(methodKey)) {//事前拦截
					map = (Map) plugin.beforeInvoke(vo.getParams());
				} else if (Validator.isNotNull(methodKey) && "afterMethodKey".equalsIgnoreCase(methodKey)) {//事后拦截
					map = (Map) plugin.afterInvoke(vo.getParams());
				} else if (Validator.isNotNull(methodKey) && "invokeMethodKey".equalsIgnoreCase(methodKey)) {//事中拦截
					map = (Map) plugin.doInvoke(vo.getParams());
				}
				if (!Validator.isEmpty(map))
					resultmap.putAll(map);
			}
		}
		return resultmap;
	}

	/**
	 * @param plugins 系统启动加载插件组合
	 */
	@SuppressWarnings("unchecked")
	public void setPlugins(Map<String, String> plugins) {
		log.info("插件数据加载start");
		try {
			if (!IusSqlTools.getInstance().getPluginsCache().checkCacheObject("plugins_open_mark")) {
				if (!DynamicDataSource.getInstance().checkDataSource("plateform")) {
					DynamicDataSource.getInstance().addDataSource("plateform");
				}
				DynamicDataSourceHolder.putDataSource("plateform");
				MethodParam param = new MethodParam("SysPluginGroup", "", "", IusSqlTools.SPANCENAME);
				List<DataMap> list = iusPubDao.select(param);
				if (!Validator.isEmpty(list)) {
					IusSqlTools.getInstance().getPluginsCache().createCacheObject("plugins_open_mark", "true");
					Map<String, String> map = new HashMap<>(list.size());
					int count = list.size();
					for (int i = 0; i < count; i++) {
						DataMap mp = list.get(i);
//						log.info("加载["+String.valueOf(mp.get("sysName"))+"]的组合"+String.valueOf(mp.get("rulesCode"))+"-"+String.valueOf(mp.get("rulesRemark")));
						String cacheKey = plugins_cache_key + String.valueOf(mp.get("rulesCode"));
						IusSqlTools.getInstance().getPluginsCache().createCacheObject(cacheKey,
								String.valueOf(mp.get("rulesName")));
					}
					log.info("加载了["+count+"]条插件组合数据");
				}
			}
			CustomMethodFactory.getInstance().init();
			log.info("插件数据加载end");
		} catch (Exception e) {
			log.error("加载插件数据出错 ", e);
		}
	}

	public void setPluginInfo(String key, String value) {//添加或删除插件组合
		String cacheKey = plugins_cache_key + key;
		IusSqlTools.getInstance().getPluginsCache().removeCacheObject(cacheKey);
		if (Validator.isNotNull(value)) {
			IusSqlTools.getInstance().getPluginsCache().createCacheObject(cacheKey, value);
		}
	}

	private String getPlugins(String key) {
		String cacheKey = plugins_cache_key + key;
		String value = String.valueOf(IusSqlTools.getInstance().getPluginsCache().getCacheObjectByKey(cacheKey));
		return value;
	}

	public void setIusPubDao(IDao iusPubDao) {
		this.iusPubDao = iusPubDao;
	}
}
